from django.shortcuts import render
from rest_framework.generics import ListAPIView,CreateAPIView,UpdateAPIView,DestroyAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_extensions.cache.decorators import cache_response
from rest_framework_extensions.cache.mixins import CacheResponseMixin
# Create your views here.
from areas.models import Area
from areas.serializers import AreasSerializer, AddressSerializer
from users.models import Address


class AreasView(CacheResponseMixin,ListAPIView):
    '''获取所有省的信息'''

    serializer_class = AreasSerializer
    # queryset = Area.objects.filter(parent=None)
    queryset = Area.objects.filter(parent=None)


class AreaView(CacheResponseMixin,ListAPIView):
    '''获取所有市的信息和区县的信息'''

    serializer_class = AreasSerializer
    # queryset = Area.objects.filter(parent_id=pk)

    # 重写查询集
    def get_queryset(self):
        # 获取路由中的pk值
        pk = self.kwargs['pk']
        return Area.objects.filter(parent_id=pk)


class AddressView(CreateAPIView,ListAPIView,UpdateAPIView):
    '''保存地址'''
    # 指定序列化器
    serializer_class = AddressSerializer
    # queryset = Address.objects.filter(user=self.request.user)

    def get_queryset(self):
        return Address.objects.filter(user=self.request.user,is_deleted=False)

    def delete(self,request,pk):
        obj = self.get_object()

        obj.is_deleted = True
        obj.save()

        return Response()

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response({'addresses': serializer.data,
                         'default_address_id': self.request.user.default_address_id})


class Address1View(APIView):
    '''设置默认地址'''
    def put(self,request,pk):
        # 获取用户对象
        user = request.user
        user.default_address_id = pk
        user.save()
        return Response({'default_address_id' : pk})


# class









